package com.splant.android.smart.UILevel.Community.fragments;

import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.sPlantRequestParams;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.DeviveMessages;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.CustomDialog;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.WheelView.WheelView;
import com.splant.android.smart.SystemDefinedLevel.SlidingLayout.SlidingLayout;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.Garden_AddTimerWaters_Activity;
import com.splant.android.smart.UILevel.Community.Garden_DetectorList_Activity;
import com.splant.android.smart.UILevel.Community.Garden_DeviceList_Search_Activity;
import com.splant.android.smart.UILevel.Community.Garden_MessageList_Activity;
import com.splant.android.smart.UILevel.Community.Garden_WaterRecord_Activity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/21.
 */

public class Garden_Plants_Fragment extends Fragment implements View.OnClickListener {

    private ImageButton imgBtn_drawermenu;
    private TextView tv_openAllDevices;
    private TextView tv_closeAllDevices;
    private TextView tv_inspectionRecord;
    private TextView tv_wateredRecord;
    private TextView tv_mapOrListMode;
    private TextView tv_abnormal;
    private View mView;
    private RadioGroup rdogp_deviceList;
    private RadioButton rdoBtn_waterList;
    private RadioButton rdoBtn_detectorList;
    private FragmentManager fm;
    private TextView tv_areaName;
    private TextView tv_waterStrategy;
    private EditText edt_searchKey;
    private ImageButton imgBtn_msg;
    private LinearLayout ll_drawermenu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_plants_activity, null);

            rdogp_deviceList = (RadioGroup) mView.findViewById(R.id.rdogp_deviceList);
            rdoBtn_waterList = (RadioButton) mView.findViewById(R.id.rdoBtn_waterList);
            rdoBtn_detectorList = (RadioButton) mView.findViewById(R.id.rdoBtn_detectorList);
            imgBtn_drawermenu = (ImageButton) mView.findViewById(R.id.imgBtn_drawermenu);
            ll_drawermenu = (LinearLayout) mView.findViewById(R.id.ll_drawermenu);
            tv_openAllDevices = (TextView) mView.findViewById(R.id.tv_openAllDevices);
            tv_closeAllDevices = (TextView) mView.findViewById(R.id.tv_closeAllDevices);
            tv_inspectionRecord = (TextView) mView.findViewById(R.id.tv_inspectionRecord);
            tv_wateredRecord = (TextView) mView.findViewById(R.id.tv_wateredRecord);
            tv_mapOrListMode = (TextView) mView.findViewById(R.id.tv_mapOrListMode);
            tv_abnormal = (TextView) mView.findViewById(R.id.tv_abnormal);
            tv_areaName = (TextView) mView.findViewById(R.id.tv_areaName);
            tv_waterStrategy = (TextView) mView.findViewById(R.id.tv_waterStrategy);
            edt_searchKey = (EditText) mView.findViewById(R.id.edt_searchKey);
            imgBtn_msg = (ImageButton) mView.findViewById(R.id.imgBtn_msg);

            init();

            tv_openAllDevices.setOnClickListener(this);
            tv_closeAllDevices.setOnClickListener(this);
            tv_wateredRecord.setOnClickListener(this);
            tv_inspectionRecord.setOnClickListener(this);
            tv_mapOrListMode.setOnClickListener(this);
            imgBtn_drawermenu.setOnClickListener(this);
            rdogp_deviceList.setOnCheckedChangeListener(menuChangeChick);
            tv_areaName.setOnClickListener(this);
            tv_waterStrategy.setOnClickListener(this);
            edt_searchKey.setOnClickListener(this);
            imgBtn_msg.setOnClickListener(this);
            ll_drawermenu.setOnClickListener(this);
        }
        return mView;
    }

    private Fragment waterListFragment;
    private sPlantAsyncHttpClient sPlantClient;
    private LoadingDialog loadingDialog;

    private void init() {

        sPlantClient = sPlantAsyncHttpClient.getInstance();
        rdoBtn_detectorList.setBackgroundResource(R.color.garden_color0);

        loadingDialog = LoadingDialog.createDialog(getActivity());

        fm = getChildFragmentManager();
        waterListFragment = fm.findFragmentByTag("waterList");

        if (waterListFragment == null) {
            FragmentTransaction ft = fm.beginTransaction();
            waterListFragment = new Garden_WaterList_Fragment();
            ft.add(R.id.fl_devicelist_content, waterListFragment, "waterList");
            ft.commit();
        }

        if (Global.user != null) {

            if (Global.user.getIsMsg())
                tv_abnormal.setVisibility(View.VISIBLE);

        }
    }

    public void updateMenuIconState(boolean state) {

        if (isAdded()) {
            if (state)
                imgBtn_drawermenu.setBackgroundResource(R.mipmap.garden_ic_drawermenu_close);
            else
                imgBtn_drawermenu.setBackgroundResource(R.mipmap.garden_ic_drawermenu_open);
        }

    }

    private SlidingLayout slidingLayout;

    public void setSlidingLayout(SlidingLayout slidingLayout) {
        this.slidingLayout = slidingLayout;
    }

    @Override
    public  void onActivityResult(int requestCode, int resultCode, Intent data)  {
        super.onActivityResult(requestCode, resultCode,  data);

        if (requestCode==0)
        {
            tv_abnormal.setVisibility(View.GONE);
        }

    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.imgBtn_drawermenu:
                if (slidingLayout != null) {
                    if (slidingLayout.isLeftLayoutVisible()) {
                        slidingLayout.scrollToRightLayout();
                    } else {
                        slidingLayout.scrollToLeftLayout();
                    }
                }
                break;
            case R.id.tv_mapOrListMode:

                FragmentTransaction ft = fm.beginTransaction();
                Fragment waterList = fm.findFragmentByTag("waterList");
                Fragment detectorList = fm.findFragmentByTag("detectorList");
                Fragment mapMode = fm.findFragmentByTag("mapMode");

                if (waterList != null)
                    ft.hide(waterList);
                if (detectorList != null)
                    ft.hide(detectorList);

                if (rdogp_deviceList.getVisibility() == View.VISIBLE) {

                    rdogp_deviceList.setVisibility(View.GONE);
                    tv_mapOrListMode.setBackgroundResource(R.color.garden_color1);
                    tv_mapOrListMode.setText("列表模式");

                    if (mapMode == null) {
                        mapMode = new Garden_Map2_Fragment();
                        ft.add(R.id.fl_devicelist_content, mapMode, "mapMode");
                    } else {
                        ft.show(mapMode);
                        ((Garden_Map2_Fragment) mapMode).selectArea();
                    }
                    ((Garden_Map2_Fragment) mapMode).showBtn();
                    selectIndex = 2;
                } else {

                    rdogp_deviceList.setVisibility(View.VISIBLE);
                    tv_mapOrListMode.setBackgroundResource(R.color.garden_color0);
                    tv_mapOrListMode.setText("地图模式");

                    if (mapMode != null) {
                        ((Garden_Map2_Fragment) mapMode).hideBtn();
                        ft.hide(mapMode);
                    }
                    if (rdoBtn_waterList.isChecked() && waterList != null) {
                        ft.show(waterList);
                        selectIndex = 0;
                        ((Garden_WaterList_Fragment) waterList).selectArea();
                    } else if (rdoBtn_detectorList.isChecked() && detectorList != null) {
                        ft.show(detectorList);
                        selectIndex = 1;
                        ((Garden_DetectorList_Fragment) detectorList).selectArea();
                    } else {
                        waterList = new Garden_WaterList_Fragment();
                        ft.add(R.id.fl_devicelist_content, waterList, "waterList");
                        selectIndex = 0;
                    }
                }
                ft.commit();
                break;
            case R.id.tv_areaName:
                showAreaList();
                break;
            case R.id.tv_closeAllDevices:
                if (selectIndex == 0 || selectIndex == 2)
                    closeAllSwitchs();
                break;
            case R.id.tv_openAllDevices:
                if (selectIndex == 0 || selectIndex == 2)
                    openAll();
                break;
            case R.id.tv_waterStrategy:
                Intent intent2 = new Intent(getActivity(), Garden_AddTimerWaters_Activity.class);
                startActivity(intent2);
                break;
            case R.id.tv_inspectionRecord:
                Intent intent = new Intent(getActivity(), Garden_DetectorList_Activity.class);
                startActivity(intent);
                break;
            case R.id.tv_wateredRecord:
                Intent intent1 = new Intent(getActivity(), Garden_WaterRecord_Activity.class);
                startActivity(intent1);
                break;
            case R.id.edt_searchKey:
                Intent intent3 = new Intent(getActivity(), Garden_DeviceList_Search_Activity.class);
                startActivity(intent3);
                break;
            case R.id.imgBtn_msg:
                Intent intent4 = new Intent(getActivity(), Garden_MessageList_Activity.class);
                startActivityForResult(intent4,0);
                break;
            case R.id.ll_drawermenu:

                if (slidingLayout != null) {

                    if (slidingLayout.isLeftLayoutVisible()) {
                        slidingLayout.scrollToRightLayout();
                    } else {
                        slidingLayout.scrollToLeftLayout();
                    }

                }

                break;

        }
    }

    private void closeAllSwitchs() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle("提示信息");
        builder.setMessage("您确定关闭该区域所有开关？");
        builder.setPositiveButton(getString(R.string.system_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                closeAll();
            }
        });
        builder.setNegativeButton(getString(R.string.system_cancel), new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private List<AreaListBean.Area> areaList = new ArrayList<>();

    private void showAreaList() {

        View popupView = getActivity().getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(getActivity(), 200), System_Dimen_Util.dip2px(getActivity(), 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 2);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                window.dismiss();

                String areaName = areaList.get(position).getAreaName();
                tv_areaName.setText(areaName);
                Global.selectedArea = areaList.get(position);

                FragmentTransaction ft = fm.beginTransaction();
                Fragment waterList = fm.findFragmentByTag("waterList");
                Fragment detectorList = fm.findFragmentByTag("detectorList");
                Fragment mapMode = fm.findFragmentByTag("mapMode");

                if (waterList != null && selectIndex == 0)
                    ((Garden_WaterList_Fragment) waterList).selectArea();
                else if (detectorList != null && selectIndex == 1)
                    ((Garden_DetectorList_Fragment) detectorList).selectArea();
                else if (mapMode != null && selectIndex == 2)
                    ((Garden_Map2_Fragment) mapMode).selectArea();

                ft.commit();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            if (response.getInt("succeed") == 1) {

                                Gson gson = new Gson();
                                AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                                if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {
                                    areaList.clear();

                                    areaList.addAll(areaListBean.getAreaList());

                                    if (selectIndex != 2) {
                                        AreaListBean.Area areaAll = new AreaListBean.Area();
                                        areaAll.setAreaId("");
                                        areaAll.setAreaName("全部区域");
                                        areaList.add(0, areaAll);
                                    } else {
                                        if (areaList.get(0).getAreaName().equals("全部区域")) {
                                            areaList.remove(0);
                                        }
                                    }

                                    Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(getActivity(), areaList);

                                    lv_areaList.setAdapter(garden_areaList_adapter);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                        Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();

                    }
                }
        );
    }

    private Dialog waterTimeDialog = null;
    private List<String> mDatas = new ArrayList<>();

    private int waterTime = 10;

    private List<String> getTimeData() {

        for (int i = 1; i <= 10; i++) {
            mDatas.add(i + " 分钟");
        }

        for (int i = 15; i <= 30; i+=5) {
            mDatas.add(i + " 分钟");
        }

        for (int i = 40; i <= 60; i+=10) {
            mDatas.add(i + " 分钟");
        }

        return mDatas;
    }

    private void openAll() {

        if (Global.selectedArea == null || Global.selectedArea.getAreaId().equals("")) {
            Toast.makeText(getActivity(), "请先选择区域", Toast.LENGTH_SHORT).show();
            return;
        }

        waterTime = 10;
        View outerView = LayoutInflater.from(getActivity()).inflate(R.layout.system_unit_wheel_view, null);
        WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        wv.setOffset(2);
        wv.setItems(getTimeData());
        wv.setSeletion(9);

        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                String[] items = item.split(" ");
                waterTime = Integer.parseInt(items[0]);
            }
        });

        TextView tv = new TextView(getActivity());
        tv.setText("请选择");
        tv.setTextSize(20);
        tv.setPadding(10, 10, 10, 10);
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(Color.parseColor("#ffaa66cc"));

        waterTimeDialog = new AlertDialog.Builder(getActivity())
                .setCustomTitle(tv)
                .setView(outerView)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        waterAll();

                    }
                }).create();
        waterTimeDialog.show();

        WindowManager.LayoutParams params = waterTimeDialog.getWindow().getAttributes();
        params.width = (2 * DeviveMessages.getScreenInfo(getActivity(), getActivity().getWindowManager()).getScreenWidth()) / 5;
        waterTimeDialog.getWindow().setAttributes(params);


    }

    private void closeAll() {
        waterTime = 0;
        waterAll();
    }

    private void waterAll() {

        if (Global.selectedArea == null || Global.selectedArea.getAreaId().equals("")||tv_areaName.getText().toString().equals("选择区域")) {
            Toast.makeText(getActivity(), "请先选择区域", Toast.LENGTH_SHORT).show();
            return;
        }
        sPlantRequestParams params = new sPlantRequestParams();
        params.putParams("userId", Global.user.getUserId());
        params.putParams("time", waterTime);
        params.putParams("areaId", Global.selectedArea.getAreaId());

        if (loadingDialog.isShowing() == false)
            loadingDialog.show();

        sPlantClient.post(getActivity(), sPlantAsyncHttpClient.SWITCH_ALLDEVICES, params, new sPlantJsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try
                        {
                            loadingDialog.dismiss();
                            Fragment waterList = fm.findFragmentByTag("waterList");
                            Fragment mapMode = fm.findFragmentByTag("mapMode");

                            String waterIds = response.getString("message");
                            if (waterIds == null || waterIds.equals("null")) {

                                if (selectIndex == 0 && waterList != null)
                                    ((Garden_WaterList_Fragment) waterList).openAreaDevicesSuccess(waterTime);
                                else if (selectIndex == 2 && mapMode != null)
                                {
                                    if (waterTime>0)
                                    ((Garden_Map2_Fragment) mapMode).openedAreaDevicesSuccess();
                                    else
                                    {
                                        ((Garden_Map2_Fragment) mapMode).closedAreaDeviceSuccess();
                                    }
                                }
                            } else {

                                if (selectIndex == 0 && waterList != null)
                                    ((Garden_WaterList_Fragment) waterList).openAreaDevicesFailure(waterIds, waterTime);
                                else if (selectIndex == 2 && mapMode != null)
                                    ((Garden_Map2_Fragment) mapMode).openedAreaDevicesFailure(waterIds, waterTime);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                        loadingDialog.dismiss();

                        Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }

                }
        );

    }

    private int selectIndex = 0;

    private RadioGroup.OnCheckedChangeListener menuChangeChick = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            FragmentTransaction ft = fm.beginTransaction();
            Fragment waterList = fm.findFragmentByTag("waterList");
            Fragment detectorList = fm.findFragmentByTag("detectorList");
            Fragment mapMode = fm.findFragmentByTag("mapMode");

            if (waterList != null)
                ft.hide(waterList);

            if (detectorList != null)
                ft.hide(detectorList);

            if (mapMode != null)
                ft.hide(mapMode);

            switch (checkedId)
            {
                case R.id.rdoBtn_waterList:

                    if (waterList == null) {
                        waterList = new Garden_WaterList_Fragment();
                        ft.add(R.id.fl_devicelist_content, waterList, "waterList");
                    } else
                        ft.show(waterList);

                    rdoBtn_detectorList.setBackgroundResource(R.color.garden_color0);
                    rdoBtn_waterList.setBackgroundResource(R.color.garden_color1);
                    selectIndex = 0;

                    ((Garden_WaterList_Fragment) waterList).selectArea();

                    break;
                case R.id.rdoBtn_detectorList:

                    if (detectorList == null) {
                        detectorList = new Garden_DetectorList_Fragment();
                        ft.add(R.id.fl_devicelist_content, detectorList, "detectorList");
                    } else
                        ft.show(detectorList);

                    rdoBtn_detectorList.setBackgroundResource(R.color.garden_color1);
                    rdoBtn_waterList.setBackgroundResource(R.color.garden_color0);
                    selectIndex = 1;

                    ((Garden_DetectorList_Fragment) detectorList).selectArea();
                    break;
            }
            ft.commit();
        }
    };
}
